<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Moi</title>

        <meta charset="utf-8">
        <link rel="icon" href="/static/favicon.ico">

        <script src="/static/jquery-1.3.2.js"></script>
        <script src="/static/date.js"></script>
        <script src="/static/realStorage.js"></script>
        <script src="/static/persist.js"></script>

        <style type="text/css">
            textarea {
                color: black;
                width: 80em;
                height: 40em;
            }

            a, a:visited {
                color: blue;
                padding-left: 1em;
                padding-right: 1em;
            }
        </style>
    </head>
    <body style="visibility: hidden">
        <article>
            <h1>Snippet for the week of
                <time id="current-week" datetime=""></time>
            </h1>
            <form>
                <textarea></textarea>
            </form>
        </article>
        <nav>
            <hgroup>
                <h1>Other Snippets</h1>
                <h2 id="loading-status">Loading ...</h2>
            </hgroup>
            <ol id="old-snippets">
            </ol>
        </nav>
        <script>
            var currentSnippet = null;

            function dateToStr(date) {
                return date.toString("yyyy-MM-dd");
            }

            function strToDate(str) {
                return Date.parseExact(str, "yyyy-MM-dd");
            }

            function getSnippet(date) {
                /* Return the snippet for the date, else create a new object. */
                var yearStr = date.getFullYear().toString();
                var dateStr = dateToStr(date);

                var yearSet = persist.root[yearStr];
                if (yearSet === undefined) {
                    yearSet = {};
                    persist.root[yearStr] = yearSet;
                    persist.assignGroup(yearSet, date.getFullYear());
                }

                var snippet = yearSet[dateStr];
                if (snippet === undefined) {
                    snippet = {date: dateStr, summary: "<insert text here>"};
                    yearSet[dateStr] = snippet;
                    persist.assignGroup(snippet, date.getFullYear());
                }

                return snippet;
            }

            function displaySnippet(date) {
                /* Display the current snippet. */
                currentSnippet = getSnippet(date);

                $("#current-week").attr("datetime", currentSnippet.date);
                $("#current-week").html(currentSnippet.date);

                $("textarea").val(currentSnippet.summary);
            }

            function oldSnippets(count) {
                /* Display links to old snippets. */
                var step = 100;
                while (step && count) {
                    var dateStr = dateToStr(last_monday);
                    var anchor = $(['<li><a href="#"><time datetime="', dateStr,
                                    '">', dateStr, '</time></a>'].join(''));

                    anchor.appendTo('#old-snippets');
                    anchor.bind('click', last_monday, function(evt) {
                        displaySnippet(evt.data);
                    });

                    //getSnippet(last_monday);

                    count -= 1;
                    step -= 1;
                    last_monday = last_monday.clone().moveToDayOfWeek(1, -1);
                }
                if (count) {
                    //persist.sync();
                    $('#loading-status').html("Loading ("+count+" left) ...");
                    setTimeout('oldSnippets('+count+')', 0);
                }
                else {
                    $('#loading-status').remove();
                    //setInterval('sync()', 1000);
                }
            }

            function saveSnippet() {
                /* Save the current snippet being edited. */
                currentSnippet.summary = $('textarea').val();
            }

            function sync() {
                for (var x=0; x < 100; x+=1) {
                    persist.localSync();
                }
            }

            function updateNotification(ob) {
                if (currentSnippet && ob.date && ob.date === currentSnippet.date) {
                    displaySnippet(strToDate(ob.date));
                }
            }

            // Log in if necessary.
            /*var xhr = new XMLHttpRequest();
            xhr.open('POST', '/_api/onthelist', false);
            xhr.send('/');
            if (xhr.status !== 200) {
                throw new Error("error trying to see if logged in");
            }
            else if (xhr.responseText) {
                window.location = xhr.responseText;
            }
            else {*/
                persist.onUpdate = updateNotification;
                //persist.sync();
                var today = Date.today();
                if (persist.root.__group__ !== today.getFullYear()) {
                    persist.assignGroup(persist.root, today.getFullYear());
                }
                var last_monday = null;
                if (today.getDay() === 1) {
                    last_monday = today;
                }
                else {
                    last_monday = today.moveToDayOfWeek(1, -1);
                }

                displaySnippet(last_monday);

                $('textarea').bind('keyup', saveSnippet);

                $('body').css("visibility", "visible");
                // Let execution terminate so the browser will redraw the page.
                setTimeout('oldSnippets(1000)', 0);
            //}

        </script>
    </body>
</html>
